import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:pp_uikit/tag/pp_tag_theme.dart';

// controller 待实现
class PPSelectTagController {
  List<bool> tagState = [];
  List<bool>? groupStates;
  int? singleState;
  ValueNotifier<bool> resetNotifier = ValueNotifier<bool>(false);
  ValueNotifier<bool> setupTagStateNotifier = ValueNotifier<bool>(false);
  ValueNotifier<bool> queryTagStateNotifier = ValueNotifier<bool>(false);

  // 重置选中状态
  void resetTagState() {
    var states = <bool>[];
    for (var i = 0; i < tagState.length; i++) {
      states.add(false);
    }
    tagState = states;
    resetNotifier.value = !resetNotifier.value;
  }

  // 设置选中状态
  void setupTagState({List<bool>? groupStates, int? singleState}) {
    this.groupStates = groupStates;
    this.singleState = singleState;
    setupTagStateNotifier.value = !setupTagStateNotifier.value;
  }

  // List<bool>
  void getGroupTagStates() {
    queryTagStateNotifier.value = !queryTagStateNotifier.value;
  }
}

/// 选择模式的标签组合
/// 支持流式和横向布局
/// 支持定宽和非定宽
/// 宽高间距可设置
/// 支持单选和多选
/// ignore: must_be_immutable
class PPSelectTag extends StatefulWidget {
  int itemCount;

  final String Function(int index)? tagTitleBuilder;

  /// 选择tag的回调,返回选中 tag 的位置
  final void Function(List<int> selectedList)? onSelect;

  /// 水平间距，默认 12
  final double spacing;

  /// 垂直间距，默认 10
  final double verticalSpacing;

  /// 普通标签的样式
  final TextStyle? tagTextStyle;

  /// 选中的标签样式
  final TextStyle? selectedTagTextStyle;

  /// 普通标签背景色，默认 F0Color
  final Color? tagBackgroundColor;

  /// 选中的标签背景色，默认 B0Color
  final Color? selectedTagBackgroundColor;

  /// 标签宽度。默认全局配置宽度 75
  double? tagWidth;

  /// 标签高度。默认全局配置高度 34
  final double? tagHeight;

  /// 标签个数
  int? rowCount;

  /// true 流式展示，false 横向滑动展示，默认 true
  final bool softWrap;

  /// 对齐模式，默认为 Alignment.centerLeft，靠左
  final Alignment alignment;

  /// 是否需要固定宽度，默认为true，指定为false为流式布局
  final bool fixWidthMode;

  /// 是否是单选，默认 true
  final bool isSingleSelect;

  /// 多选时的初始状态数组
  final List<bool>? initTagState;

  /// 单选时的初始状态
  final int? selectedIndex;

  PPSelectTagController? controller;

  PPTagTheme? themeData;

  PPSelectTag({
    Key? key,
    this.itemCount = 0,
    this.tagTitleBuilder,
    this.onSelect,
    this.spacing = 12,
    this.verticalSpacing = 10,
    this.tagTextStyle,
    this.selectedTagTextStyle,
    this.tagBackgroundColor,
    this.selectedTagBackgroundColor,
    this.tagWidth,
    this.tagHeight,
    this.rowCount,
    this.isSingleSelect = true,
    this.initTagState,
    this.selectedIndex,
    this.softWrap = true,
    this.alignment = Alignment.centerLeft,
    this.fixWidthMode = true,
    this.controller,
    this.themeData,
  }) : super(key: key) {
    if (isSingleSelect == true) {
      assert(initTagState == null || (initTagState!.length <= 1));
    }
    themeData ??= PPTagTheme();
    tagWidth ??= _getTagWidth(rowCount: rowCount ??= 3, rowItemSpace: spacing);
    themeData = themeData!.merge(PPTagTheme(
        tagBackgroundColor: tagBackgroundColor,
        tagTextStyle: tagTextStyle,
        selectTagTextStyle: selectedTagTextStyle,
        tagWidth: tagWidth,
        tagHeight: tagHeight,
        selectedTagBackgroundColor: selectedTagBackgroundColor));
  }

  double _getTagWidth(
      {int rowCount = 3,
      double rowItemSpace = 12,
      double leftRightPadding = 24}) {
    ScreenUtil().screenWidth;
    return (ScreenUtil().screenWidth -
            leftRightPadding -
            rowItemSpace * (rowCount - 1)) /
        rowCount;
  }

  @override
  State<StatefulWidget> createState() => _PPSelectTagState();
}

class _PPSelectTagState extends State<PPSelectTag> {
  List<bool> get _tagState {
    return _controller!.tagState;
  }

  PPSelectTagController? _controller;

  @override
  void initState() {
    super.initState();
    _initController();
    _setupInitTagState();
  }

  void _initController() {
    _controller = widget.controller;
    _controller ??= PPSelectTagController();
    // 重置状态侦听
    _controller?.resetNotifier.addListener(() {
      if (_controller?.resetNotifier.value == true) {
        // _resetTagState();
        _controller?.resetNotifier.value = false;
        setState(() {});
        if (null != widget.onSelect) {
          List<int> _selectedIndexes = [];
          widget.onSelect!(_selectedIndexes);
        }
      }
    });
    // 设置状态侦听
    _controller?.setupTagStateNotifier.addListener(() {
      if (_controller?.setupTagStateNotifier.value == true) {
        _setupTagStates(
            groupStates: _controller?.groupStates,
            singleState: _controller?.singleState);
        _controller?.setupTagStateNotifier.value = false;
        setState(() {});
        // if (null != widget.onSelect) {
        //   List<int> _selectedIndexes = [];
        //   widget.onSelect!(_selectedIndexes);
        // }
      }
    });
  }

  void _resetTagState() {
    // var states = <bool>[];
    // for (var i = 0; i < widget.itemCount; i++) {
    //   states.add(false);
    // }
    // _tagState = states;
    // _controller?.resetTagState();
  }

  void _setupInitTagState() {
    var states = <bool>[];
    for (var i = 0; i < widget.itemCount; i++) {
      states.add(false);
    }
    _controller?.tagState = states;

    if (widget.initTagState != null) {
      for (int index = 0;
          index < min(widget.initTagState!.length, widget.itemCount);
          index++) {
        _tagState[index] = widget.initTagState![index];
      }
    }
    if (widget.isSingleSelect && widget.selectedIndex != null) {
      _tagState[widget.selectedIndex!] = true;
    }
  }

  void _setupTagStates({List<bool>? groupStates, int? singleState}) {
    _resetTagState();
    if (groupStates != null) {
      for (int index = 0;
          index < min(groupStates.length, widget.itemCount);
          index++) {
        _tagState[index] = groupStates[index];
      }
    }
    if (singleState != null) {
      _tagState[singleState] = true;
    }
  }

  @override
  Widget build(BuildContext context) {
    Widget content;
    if (widget.softWrap) {
      content = Wrap(
        runSpacing: widget.verticalSpacing,
        spacing: widget.spacing,
        children: _tagWidgetList(context),
      );
    } else {
      content = _scrollTagListWidget(context);
    }

    return Align(
      child: content,
      alignment: widget.alignment,
    );
  }

  Widget _scrollTagListWidget(context) {
    var tagList = _tagWidgetList(context);
    int tagIdx = 0;
    var finalTagList = tagList.map((tag) {
      double rightPadding = (tagIdx == tagList.length - 1) ? 0 : widget.spacing;
      var padding = Padding(
        child: tag,
        padding: EdgeInsets.only(right: rightPadding),
      );
      tagIdx++;
      return padding;
    }).toList();
    return SingleChildScrollView(
        scrollDirection: Axis.horizontal,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.end,
          children: finalTagList,
        ));
  }

  List<Widget> _tagWidgetList(context) {
    List<Widget> list = [];
    if (widget.itemCount > 0) {
      if (widget.itemCount != _tagState.length) {
        _setupInitTagState();
      }

      for (int nameIndex = 0; nameIndex < widget.itemCount; nameIndex++) {
        Widget tagWidget = _tagWidgetAtIndex(nameIndex);
        GestureDetector gdt = GestureDetector(
            child: tagWidget,
            onTap: () {
              if (widget.isSingleSelect) {
                bool selected = _tagState[nameIndex];
                if (selected) {
                  return;
                }
                _controller?.tagState =
                    _tagState.map((value) => false).toList();
                setState(() {
                  _tagState[nameIndex] = true;
                });
              } else {
                setState(() {
                  _tagState[nameIndex] = !_tagState[nameIndex];
                });
              }

              if (null != widget.onSelect) {
                List<int> _selectedIndexes = [];
                for (int index = 0; index < _tagState.length; index++) {
                  if (_tagState[index]) _selectedIndexes.add(index);
                }
                widget.onSelect!(_selectedIndexes);
              }
            });
        list.add(gdt);
      }
    }

    return list;
  }

  Widget _tagWidgetAtIndex(int nameIndex) {
    bool selected = _tagState[nameIndex];
    String title = "";
    title = widget.tagTitleBuilder!(nameIndex);

    Text tx = Text(
      title,
      style: selected ? _selectedTextStyle() : _tagTextStyle(),
      overflow: TextOverflow.ellipsis,
    );
    Container container = Container(
      constraints: BoxConstraints(minWidth: widget.themeData!.tagMinWidth),
      decoration: BoxDecoration(
          color: selected
              ? (widget.themeData!.selectedTagBackgroundColor)
              : (widget.themeData!.tagBackgroundColor),
          borderRadius: BorderRadius.circular(widget.themeData!.tagRadius)),
      width: widget.fixWidthMode ? widget.themeData!.tagWidth : null,
      height: widget.themeData!.tagHeight,
      padding: const EdgeInsets.only(left: 8, right: 8),
      child: Center(widthFactor: 1, child: tx),
    );
    return container;
  }

  TextStyle _tagTextStyle() {
    return widget.themeData!.tagTextStyle;
  }

  TextStyle _selectedTextStyle() {
    return widget.themeData!.selectTagTextStyle;
  }

  @override
  void didUpdateWidget(PPSelectTag oldWidget) {
    super.didUpdateWidget(oldWidget);
    // 如果两个数组不相等,重置选中状态
    // if (!sameList(oldWidget.tags, widget.tags)) {
    //   _tagState = List.filled(widget.tags.length, false);
    // }
  }

  /// 比较两个数组内容是否一致，如果一致，返回 true，否则 false
  bool sameList(List<String> first, List<String> second) {
    if (first.length != second.length) return false;
    int index = 0;
    return first.firstWhere((item) => item != second[index++],
            orElse: () => '') ==
        '';
  }
}
